// 解构赋值
// 1、数组的解构
let fn1 = () => {
  // 一维数组，不完全解构
  let [a, , c] = [1, 2, 3]
  console.log(a, c) // 1 3
  // 多维数组
  let arr = [[1], [2], 3]
  let [[m], [n], p, o] = arr
  console.log(m, n, p, o) // 1 2 3
  // 剩余参数
  let [x, y, ...z] = [1, 2, 3, 4, 5, 6]
  console.log(x, y, z) // 1 2 [ 3, 4, 5, 6 ]
  // 解构默认值
  let [q, w, e = 3] = [1, 2]
  console.log(q, w, e) // 1 2 3
}

// 2、对象的解构
let fn2 = () => {
  // 普通对象属性解构
  let { bar, foo, dff } = { foo: 'aaa', bar: 'bbb' }
  console.log(bar, foo, dff) // bbb aaa undefined
  // 从内置对象中取属性和方法使用
  let { abs, sqrt, min, max, random } = Math
  console.log(abs(-100))
  console.log(sqrt(100))
  console.log(min(0, 1, -1))
  console.log(max(0, 1, -1))
  console.log(random() * 10)
  // 对象解构后起别名
  let { now: n } = Date
  console.log(n())
  // let { data: res } = await request(opt)
}

// 3. 嵌套结构的解构
let fn3 = () => {
  let obj = { p: ['Hello', { y: 'World' }] }
  let {
    p: [m, { y }],
  } = obj
  console.log(m, y)
}

// 4. 字符串的解构赋值
let fn4 = () => {
  let [a, b, c, d, e] = 'hello'
  let { length: len } = 'hello'
  console.log(a, b, c, d, e, len) // h e l l o 5
}

// 5. 数字和布尔值的解构
let fn5 = () => {
  let { toString: s } = Number('123')
  console.log(s.call(123))
  let bool = Boolean('false')
  console.log(bool)
}

// 6. 函数参数的解构赋值
let fn6 = () => {
  // 传递数组
  let f1 = ([x, y]) => {
    console.log(x + y) // 3
  }
  f1([1, 2])
  // 传递对象
  let f2 = ({ a, b, c = 3 }) => {
    console.log(a + b + c) // 6
  }
  f2({ a: 1, b: 2 })
  // 传递多个参数
  let f3 = (...x) => {
    console.log(x) // [ 1, 2, 3, 4, 5 ]
    console.log(x.reduce((p, n) => p + n)) // 15
  }
  f3(1, 2, 3, 4, 5)
}

// 7. 解构Map集合
let fn7 = () => {
  // 定义map集合
  let map = new Map([
    ['a', 1],
    ['b', 2],
    ['c', 3],
  ])
  // 设置值,添加值
  map.set('d', 4)
  console.log(map)
  // 通过key获取值
  console.log(map.get('d'))
  // 使用for-of遍历map
  for (let [k, v] of map) {
    console.log(k, v)
  }
}

// 8. 模块解构
import { add } from './a.js'
let fn8 = () => {
  console.log(add(1, 2))
}
fn8()
